<template>
  <a-spin :loading="spinLoading" :size="35" class="w-[100%]" tip="正在处理, 请稍候...">
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <!-- 基本信息区域 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4 text-[var(--color-text-1)]">基本信息</h2>
        <a-form
            ref="formRef"
            :model="form"
            :rules="rules"
            auto-label-width
            layout="vertical"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="townName" label="镇街名称" required>
                <a-input v-model="form.townName" placeholder="请输入镇街名称"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="townPerson" label="镇街联系人" required>
                <a-input v-model="form.townPerson" placeholder="请输入镇街联系人"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="townMobile" label="镇街联系方式" required>
                <a-input
                    v-model="form.townMobile"
                    placeholder="请输入镇街联系方式"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="townCode" label="镇街代码">
                <a-input v-model="form.townCode" placeholder="请输入镇街代码"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="townAddress" label="镇街地址">
                <a-input v-model="form.townAddress" placeholder="请输入镇街地址"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="status" label="账号状态">
                <a-select v-model="form.status" placeholder="请选择账号状态">
                  <a-option
                      v-for="(d, index) in dicts[proxy.DICT.commonNumberStatus]"
                      :key="index"
                      :label="d.dictValue"
                      :value="parseInt(d.dictKey)"
                  />
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <!-- 修改时，只询问是否重置密码，选择重置密码后，才能手动输入密码 -->
          <a-form-item
              v-if="props.params.operationType === proxy.operationType.update.type"
              class="w-[49%]"
              field="townPassword"
              row-class="form-label"
          >
            <template #label>
              <template class="flex items-center justify-between">
                <span>
                  用户密码
                  <a-tooltip
                      content="勾选重置密码后可输入密码进行重置，不勾选表示不修改密码"
                  >
                    <icon-question-circle style="color: var(--color-text-4)"/>
                  </a-tooltip>
                </span>
                <a-checkbox
                    v-model="isResetPassword"
                    :value="true"
                    @change="isResetPasswordChange"
                >重置密码
                </a-checkbox
                >
              </template>
            </template>
            <!-- 密码框 -->
            <a-input-password
                v-model="form.townPassword"
                :disabled="!isResetPassword"
                placeholder="用户密码"
            />
          </a-form-item>
          <!-- 新增时直接显示密码输入框 -->
          <a-form-item
              v-else
              field="townPassword"
              label="用户密码"
              required
          >
            <a-input-password
                v-model="form.townPassword"
                placeholder="请输入用户密码"
            />
          </a-form-item>
        </a-form>
      </div>

      <!-- 证件信息区域 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4 text-[var(--color-text-1)]">证件信息</h2>

        <!-- 图片展示区域 -->
        <a-row :gutter="16">
          <!-- 营业执照 -->
          <a-col :span="8" class="mb-4">
            <a-card title="营业执照">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.townBusinessLicense
                    "
                      type="text"
                      @click="townBusinessLicenseVisiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.townBusinessLicense
                    "
                      type="text"
                      @click="onDownLoad(form.townBusinessLicense)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="townBusinessLicenseUploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="
                    form.townBusinessLicense && form.townBusinessLicenseUrl
                  "
                    :preview-visible="townBusinessLicenseVisiable"
                    :src="form.townBusinessLicenseUrl"
                    width="100%"
                    @preview-visible-change="townBusinessLicenseVisiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>

          <!-- 组织机构代码证 -->
          <a-col :span="8" class="mb-4">
            <a-card title="组织机构代码证">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.townCode
                    "
                      type="text"
                      @click="townCodeVisiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.townCodeFile
                    "
                      type="text"
                      @click="onDownLoad(form.townCodeFile)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="townCodeUploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="form.townCodeFile && form.townCodeFileUrl"
                    :preview-visible="townCodeVisiable"
                    :src="form.townCodeFileUrl"
                    width="100%"
                    @preview-visible-change="townCodeVisiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>

          <!-- 授权委托书 -->
          <a-col :span="8" class="mb-4">
            <a-card title="授权委托书">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.townAttorney
                    "
                      type="text"
                      @click="townAttorneyVisiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.townAttorney
                    "
                      type="text"
                      @click="onDownLoad(form.townAttorney)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="townAttorneyUploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg,.pdf"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="form.townAttorney && form.townAttorneyUrl"
                    :preview-visible="townAttorneyVisiable"
                    :src="form.townAttorneyUrl"
                    width="100%"
                    @preview-visible-change="townAttorneyVisiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 操作按钮区域 -->
      <div class="flex justify-end mt-8">
        <a-space>
          <a-button class="px-6" @click="cancelBtnClick()">取消</a-button>
          <a-button class="px-6" type="primary" @click="okBtnClick()">确定</a-button>
        </a-space>
      </div>
    </div>
  </a-spin>
</template>

<script setup>
import {getCurrentInstance, reactive, ref, watch} from "vue";
import {fileSource} from "~/utils/sys.js";
import uploadFile from "~/components/uploadFile/index.vue";

//全局实例
const {proxy} = getCurrentInstance();
//加载字典
const dicts = proxy.LoadDicts([proxy.DICT.commonNumberStatus]);
//接收父组件参数
const props = defineProps({
  params: {
    type: Object,
    default: () => {
    },
  },
});
//父组件函数
const emits = defineEmits(["ok", "cancel"]);
//加载中...
const spinLoading = ref(false);
//表单ref
const formRef = ref(null);
//是否重置密码
const isResetPassword = ref(false);
//是否重置密码 change事件
const isResetPasswordChange = (val) => {
  isResetPassword.value = val;
};
const fs = fileSource.lindi_town_registration_img.key;
//默认图片
const defaultImageUrl =
    "https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp";
//图片预览状态
const townBusinessLicenseVisiable = ref(false);
const townCodeVisiable = ref(false);
const townAttorneyVisiable = ref(false);
//文件上传组件
const townBusinessLicenseUploadfFileRef = ref(null);
const townCodeUploadfFileRef = ref(null);
const townAttorneyUploadfFileRef = ref(null);

// 模拟数据
const mockTownData = {
  "1": {
    townAccountId: "1",
    townName: "安海镇",
    townPerson: "张三",
    townMobile: "13800138001",
    townCode: "350582101",
    townAddress: "福建省泉州市晋江市安海镇",
    status: 1,
    townBusinessLicense: "file_001",
    townBusinessLicenseUrl: "https://via.placeholder.com/300x200?text=营业执照",
    townCodeFile: "file_002",
    townCodeFileUrl: "https://via.placeholder.com/300x200?text=组织机构代码证",
    townAttorney: "file_003",
    townAttorneyUrl: "https://via.placeholder.com/300x200?text=授权委托书"
  },
  "2": {
    townAccountId: "2",
    townName: "磁灶镇",
    townPerson: "李四",
    townMobile: "13800138002",
    townCode: "350582102",
    townAddress: "福建省泉州市晋江市磁灶镇",
    status: 1,
    townBusinessLicense: "file_004",
    townBusinessLicenseUrl: "https://via.placeholder.com/300x200?text=营业执照",
    townCodeFile: "file_005",
    townCodeFileUrl: "https://via.placeholder.com/300x200?text=组织机构代码证",
    townAttorney: "file_006",
    townAttorneyUrl: "https://via.placeholder.com/300x200?text=授权委托书"
  }
};

//表单
const form = reactive({
  //镇街账号ID
  townAccountId: null,
  //镇街名称
  townName: null,
  //镇街联系人
  townPerson: null,
  //镇街联系方式
  townMobile: null,
  //镇街代码
  townCode: null,
  //镇街地址
  townAddress: null,
  //镇街用户密码
  townPassword: null,
  //营业执照
  townBusinessLicense: null,
  townBusinessLicenseUrl: null,
  //组织机构代码证文件
  townCodeFile: null,
  townCodeFileUrl: null,
  //授权委托书
  townAttorney: null,
  townAttorneyUrl: null,
  //状态 0-禁用 1-正常
  status: 1,
});

//表单校验规则
const rules = {
  townName: [{required: true, message: "镇街名称不能为空", trigger: "submit"}],
  townPerson: [
    {required: true, message: "镇街联系人不能为空", trigger: "submit"},
  ],
  townMobile: [
    {required: true, message: "镇街联系方式不能为空", trigger: "submit"},
  ],
  townPassword: [
    {required: true, message: "用户密码不能为空", trigger: "submit"},
  ],
};

//下载文件
const onDownLoad = (fileId) => {
  if (!fileId) {
    proxy.$msg.warning("文件不存在");
    return;
  }

  spinLoading.value = true;
  // 模拟下载
  setTimeout(() => {
    proxy.$msg.success("文件下载成功");
    spinLoading.value = false;
  }, 1000);
};

//确定按钮 -> 点击事件
const okBtnClick = () => {
  formRef.value.validate((errors) => {
    if (errors) {
      return;
    }
    spinLoading.value = true;
    
    // 模拟API调用
    setTimeout(() => {
      if (props.params.operationType === proxy.operationType.add.type) {
        // 新增逻辑
        proxy.$msg.success(proxy.operationType.add.success);
      } else if (props.params.operationType === proxy.operationType.update.type) {
        // 修改逻辑
        proxy.$msg.success(proxy.operationType.update.success);
      }
      spinLoading.value = false;
      emits("ok");
    }, 1000);
  });
};

//取消按钮 -> 点击事件
const cancelBtnClick = () => {
  emits("cancel");
};

//加载镇街账号详细信息
const loadTownAccountInfo = (townAccountId) => {
  spinLoading.value = true;
  
  // 模拟API调用
  setTimeout(() => {
    const data = mockTownData[townAccountId];
    if (data) {
      //数据赋值
      for (let key in data) {
        if (form.hasOwnProperty(key)) {
          form[key] = data[key];
        }
      }
    }
    spinLoading.value = false;
  }, 500);
};

//监听参数变化
watch(
    () => props.params,
    (newVal, oldVal) => {
      //镇街账号ID
      if (props.params.townAccountId) {
        //加载镇街账号详情
        loadTownAccountInfo(props.params.townAccountId);
      }
    },
    {deep: true, immediate: true}
);
</script>

<style scoped>
/* 图片容器样式 */
.image-container {
  @apply h-40 flex justify-center items-center;
}

/* 空图片占位符 */
.empty-image-placeholder {
  @apply w-full h-40 flex flex-col justify-center items-center border border-dashed border-[var(--color-border-2)] rounded bg-[var(--color-fill-1)];
}

/* 统一图片容器高度 */
:deep(.arco-image) {
  @apply h-40 overflow-hidden;
}

:deep(.arco-image-img) {
  @apply object-contain h-4/5;
}

/* 卡片样式调整 */
:deep(.arco-card-body) {
  @apply p-2;
}

:deep(.arco-card-header) {
  @apply pb-2;
}

/* 按钮样式优化 */
:deep(.arco-btn) {
  @apply transition-all duration-300;
}

:deep(.arco-btn-text) {
  @apply hover:bg-[var(--color-fill-2)] rounded-full w-8 h-8 flex items-center justify-center p-0 mx-1;
}

/* 卡片标题样式 */
:deep(.arco-card-header-title) {
  @apply text-[var(--color-text-1)] font-medium;
}
</style>